<template>
    <div class="desgin">
        <div class="canvasbox" style="flex-grow: 1">
            <div class="button__wrapper">
              <div class="button" style="width: 80px;margin-right: 10px" @click="handleClearFocus">
                取消选中
              </div>
                <div class="button" @click="handleSave">
                    保存
                </div>
            </div>
            <div style="display: flex;justify-content: center;">
                <div chart="123" :style="{width: screenWidth + 'px', height: screenHeight + 'px' }" class="canvas" id="canvasDom">
                </div>
            </div>
        </div>
        <div class="tool">
            <div class="undo-box">
                <van-icon name="revoke" @click="handleReset('left')"/>
                <van-icon class="right" @click="handleReset('right')" name="revoke" />
            </div>
            <div class="func-box">
                <div
                    v-for="item in funcList"
                    :key="item.id"
                    :class="['func-item', item.id === currentActiveFunc ? 'active' : '']"
                    @click="handleChangeFunc(item)">
                    <img :src="item.id === currentActiveFunc ? item.select_img : item.img" alt="">
                    <p>{{ item.mame }}</p>
                </div>
            </div>
        </div>
        <!-- 素材 -->
        <van-popup overlay-class="overlay-class" v-model="show2" position="bottom" >
            <div class="popup popup2">
                <div class="header">
                    <van-tabs v-model="tabActiveName2" @click="handleChangeSucaiTab">
                        <van-tab v-for="item in tabsList2" :key="item.id" :name="item.id" :title="item.name"></van-tab>
                    </van-tabs>
                </div>
                <div class="content">
                    <van-list
                        v-model="loading2"
                        :finished="finished2"
                        finished-text="没有更多了"
                        @load="onLoad2"
                    >
                        <div class="data2-list">
                            <div style="width: 20%;padding: 5px"
                                 v-for="item in dataList2" :key="item.id"
                                @click="handleAddSucai(item)">
                                <van-image
                                    width="100%"
                                    height="50px"
                                    :src="item.imgUrl"
                                />
                            </div>
                        </div>
                    </van-list>
                </div>
            </div>
        </van-popup>
        <!-- 文本配置 -->
        <van-popup  :overlay="false" overlay-class="overlay-class" v-model="show3" position="bottom" >
            <div class="popup popup3">
                <div class="header2">
                    <van-tabs
                        v-if="tabsList33.length && currentActiveFunc3 === '3'"
                        style="width: 100%"
                        @click="handleChangeFont"
                        background="#F6F6F6"
                        title-active-color="#00C65A"
                        title-inactive-color="#303030"
                        v-model="tabActiveName33">
                        <van-tab v-for="item in tabsList33" :key="item.id" :name="item.id" :title="item.name"></van-tab>
                    </van-tabs>
                    <van-slider
                        v-show="currentActiveFunc3 === '4'"
                        v-model="textNode.font.fontSize" active-color="#00C65A" @change="handleChangeFOntSisze">
                    </van-slider>
                    <van-tabs
                        @click="handleChangeFontColor"
                        background="#F6F6F6"
                        title-active-color="#00C65A"
                        title-inactive-color="#303030"
                        v-model="tabActiveName34" v-show="currentActiveFunc3 === '5'">
                        <van-tab v-for="item in tabsList34" :key="item.id" :name="item.id" :title="item.name">
                            <template #title>
                                <div class="color-icon-box">
                                    <span class="color-icon" :style="{ background: item.name }"></span>
                                </div>
                            </template>
                        </van-tab>
                    </van-tabs>

                </div>
                <div class="content">
                    <div class="tool">
                        <div class="func-box">
                            <div
                                v-for="item in funcList3"
                                :key="item.id"
                                :class="['func-item', item.id === currentActiveFunc3 ? 'active' : '']"
                                @click="handleChangeFunc3(item)">
                                <img :src="item.id === currentActiveFunc3 ? item.select_img : item.img" alt="">
                                <p>{{ item.mame }}</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </van-popup>
        <!-- 输入文字文本 -->
        <van-popup  overlay-class="overlay-class" v-model="show4" position="bottom">
            <div class="popup popup4">
                <div class="header">
                    <div class="button" @click="handleConfirmText">
                        完成
                    </div>
                </div>
                <div class="field-content">
                    <van-field  autosize type="textarea" ref="field" v-model="inputValue" :input-align="inputAlign" label="" placeholder="" />
                </div>
                <div class="field-direction">
                    <van-image
                        @click="handleChangeInputAlign('left')"
                        width="24px"
                        height="24px"
                        src=""
                        :src="inputAlign === 'left' ? imageBox.leftActive : imageBox.left"
                    />
                    <van-image
                        @click="handleChangeInputAlign('center')"
                        width="24px"
                        height="24px"
                        src=""
                        :src="inputAlign === 'center' ? imageBox.centerActive : imageBox.center"
                    />
                    <van-image
                        @click="handleChangeInputAlign('right')"
                        width="24px"
                        height="24px"
                        src=""
                        :src="inputAlign === 'right' ? imageBox.rightActive : imageBox.right"
                    />
                </div>
            </div>
        </van-popup>
        <!-- 素材配置 -->
        <van-popup  :overlay="false" overlay-class="overlay-class" v-model="show5" position="bottom">
            <div class="popup popup5">
                <div class="content">
                    <div class="tool">
                        <div class="func-box">
                            <div
                                v-for="item in sucaiConfigFuncList"
                                :key="item.id"
                                :class="['func-item', item.id === currentActiveSucaiConfig ? 'active' : '']"
                                @click="handleChangeSucaiConfigFunc(item)">
                                <img :src="item.id === currentActiveSucaiConfig ? item.select_img : item.img" alt="">
                                <p>{{ item.mame }}</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </van-popup>
        <!-- 图片裁剪 -->
        <van-popup overlay-class="overlay-class" v-model="show6" position="bottom">
            <ClipDesgin v-if="show6" :image-url="currentClipImageUrl" :fixed-number="fixedNumber" @get-url="handleGetClipImageRes"></ClipDesgin>
        </van-popup>
    </div>
</template>

<script>
// 配置项
const width = isNaN(parseInt(localStorage.getItem('width'))) ? 0 : parseInt(localStorage.getItem('width'))
const height = isNaN(parseInt(localStorage.getItem('height'))) ? 0 : parseInt(localStorage.getItem('height'))
const canvasOptions = {
    width: width,
    height: height,
    lineName: 'line',
    minScale: 0,
    maxScale: 50,
    // 连线颜色
    color: '#fff',
    font: {
        color: '#fff',
        fontSize: 12,
        textBaseline: 'bottom'
    },
    // 键盘事件 如 删除 移动
    keydown: -1,
    // 缩放 如 ctrl + mousewheel 缩放
    disableScale: true,
    // 移动 如 ctrl + mouse 移动
    disableTranslate: false,
    disableEmptyLine: false,
    autoAnchor: false,
    autoExpandDistance: 0,
    cacheLen: 10000,
    hideAnchor: true // 隐藏锚点
}
import {Topology} from '@/canvas/@topology/core'
import axios from 'axios'
import {Toast} from 'vant'

import left from '@/assets/left.png'
import leftActive from '@/assets/left_active.png'

import center from '@/assets/center.png'
import centerActive from '@/assets/center_active.png'

import right from '@/assets/right.png'
import rightActive from '@/assets/right_active.png'
import mixins from './mixin'
import ClipDesgin from './clip-desgin'

export default {
    name: "createdesgin",
     mixins: [mixins],
    components: {
        ClipDesgin
    },
    data() {
        return {
            screenWidth: canvasOptions.width,
            screenHeight: canvasOptions.height,
            /**
             *  路由传参数
             */
            templateCardId: null,
            templateCardImageUrl: '',
            title: '',
            cardDetail: {},
            /**
             *
             */
            canvas: null,
            currentActiveFunc: '1',
            // 素材
            show2: false,
            tabActiveName2: 1,
            tabsList2: [
            ],
            sucaiItem: null,
            loading2: false,
            finished2: false,
            pageNo2: 1,
            pageSize2: 20,
            total2: 0,
            dataList2: [
            ],
            // 文本
            show3: false,
            currentActiveFunc3: '',
            tabsList33: [
                // {
                //     id: 'Test2',
                //     name: '微软雅黑',
                //     url: "https://hekas.oss-cn-hangzhou.aliyuncs.com/fonts/RoxieRossa.ttf"
                // },
                // {
                //     id: 'RoxieRossa',
                //     name: 'RoxieRossa',
                //     url: "https://hekas.oss-cn-hangzhou.aliyuncs.com/fonts/RoxieRossa.ttf"
                // },
                // {
                //     id: 'yishu',
                //     name: '艺术字',
                //     url: 'https://hekas.oss-cn-hangzhou.aliyuncs.com/fonts/%E7%91%9E%E7%BE%8E%E5%8A%A0%E5%BC%A0%E6%B8%85%E5%B9%B3%E7%A1%AC%E7%AC%94%E6%A5%B7%E4%B9%A6.ttf'
                // }
            ],
            // 颜色
            tabActiveName34: '',
            /**
             *  当前文本的事件
             */
            textNodeEvent: '',
            textNode: {
                text: '',
                font: {
                    fontSize: 14,
                    textAlign: 'center'
                }
            },
            inputAlign: 'center',
            inputValue: '',
            imageBox: {
                left,
                leftActive,
                center,
                centerActive,
                right,
                rightActive
            },
            // 输入文本
            show4: false
        }
    },
    mounted() {
        this.initRouteQuery()
        this.getSucaiType()
    },
    methods: {

        /**
         *  保存
         */
        handleSave() {
            Toast.loading({
                message: '保存中',
                duration: 0,
              forbidClick: true
            })
            this.handleSaveImage().then(res => {
                setTimeout(() => {
                    wx.miniProgram.redirectTo({
                        url: '/pages/myDetail/index?id=' + res
                    })
                },1000)
            })
        },
        handleSaveImage(isUpload = false) {
            return new Promise(async (resolve,reject) => {
                let imageUrl = this.cardDetail.imgUrl
                if (!isUpload) {
                  imageUrl = await this.uploadImage()
                }
                axios({
                    method: 'POST',
                    url: this.baseUrl + '/api/v1/card/save',
                    headers: {
                        'X-UNI-TOKEN': localStorage.getItem('token'),
                    },
                    data: {
                        "configure": JSON.stringify(this.canvas.data),
                        "imgUrl": imageUrl,
                        "templateCardId": this.templateCardId || '0',
                        "title": this.cardDetail.title || ''
                    }
                }).then(res => {
                    if (res.data.code === 200) {
                        Toast.success('保存成功')
                       resolve(res.data.data)
                    } else {
                        Toast.fail(res.data.msg)
                        reject()
                    }
                }).catch((err) => {
                    Toast.fail(err || '请求出错')
                    reject()
                })
            })
        },
        /**
         *  初始化路由参数
         */
        initRouteQuery() {
            Toast.loading({
                message: '',
                duration: 0,
              forbidClick: true
            })
          const { token, templateCardId } = this.$route.query
          localStorage.setItem('token', token || '')
          this.templateCardId = templateCardId
            console.log('this.templateCardId',this.templateCardId)
          if (this.templateCardId) {
            axios({
              method: 'GET',
              url: this.baseUrl +`/api/v1/card/detail/${templateCardId}`,
              headers: {
                'X-UNI-TOKEN': localStorage.getItem('token'),
              },
            }).then(res => {
              this.cardDetail = res.data.data
              this.initCanvas()
              Toast.clear()
            })
          } else {
              console.log('没有模版id')
            setTimeout(() => {
                this.initCanvas()
            },300)
            Toast.clear()
          }
        },
        /**
         *  初始化画布
         */
        initCanvas() {
            this.canvas = null
            canvasOptions.on = this.onMessage
            this.canvas = new Topology('canvasDom', canvasOptions)
            setTimeout(() => {
              this.canvas.scaleTo(this.screenWidth / 250, { x: 0, y: 0}, true)
              this.canvas.data.bkColor = '#ffffff'
              this.canvas.render()
            },0)
        },
        onMessage(event, data) {
            console.log(event, data)
            if (data && data.id) {
                this.textNode = data
            } else {
                this.textNode = {
                    text: '',
                    font: {
                        fontSize: 12
                    }
                }
            }
          this.show2 = false
          this.show3 = false
          this.show5 = false
          this.show6 = false
            // 右侧输入框编辑状态时点击编辑区域其他元素，onMessage执行后才执行onUpdateProps方法，通过setTimeout让onUpdateProps先执行
            setTimeout(() => {
                switch (event) {
                    case 'addNode':
                        data.hideInput = true
                        break
                    case 'node':
                        console.log('node')
                        if (data.name === 'text') {
                            this.textNodeEvent = 'node'
                            setTimeout(() => {
                                if (this.textNodeEvent === 'node') {
                                    // 文本
                                    this.currentActiveFunc = '4'
                                    this.show3 = true
                                  console.log('打开文字')
                                }
                            },300)
                        } else if (data.name === 'image') {
                            this.textNodeEvent = 'node'
                            setTimeout(() => {
                                if (this.textNodeEvent === 'node') {
                                    // 素材
                                    this.currentActiveFunc = '4'
                                    this.show5 = true
                                }
                              console.log('打开素材')

                            },300)
                        }
                        break
                    case 'move':
                        if (data.some(el => el.name === 'text') || data.some(el => el.name === 'image')) {
                            this.textNodeEvent = 'move'
                        }
                        break
                }
            }, 0)
        },
      /**
       *  初始工具栏
       * @param item
       */
        handleChangeFunc(item) {
            this.currentActiveFunc = item.id
            switch (item.id) {
                case '1':
                    if (!this.textNode.id) {
                        Toast('未选中需要清除的素材')
                        this.canvas.delete()
                        return
                    }
                    // 清空所有设置
                    break
                case '2':
                    this.canvas.activeLayer.clear()
                    this.canvas.render()
                    // 打开素材
                    this.show2 = true
                    break
              // 照片上传
                case '3':
                    this.canvas.activeLayer.clear()
                    this.canvas.render()
                    Toast.loading({
                        message: '保存中',
                        duration: 0,
                      forbidClick: true
                    })
                    this.handleSaveImage(true).then(res => {
                        wx.miniProgram.postMessage({
                            data: {
                                action: 'image',
                                cardId: res
                            }
                        })
                        wx.miniProgram.redirectTo({
                            url: `/pages/desgin/edit?id=${res}`
                        })
                    })
                    break
              // 新增文本节点
                case '4':
                    this.canvas.activeLayer.clear()
                    this.canvas.render()
                    this.textNode = {
                      text: '',
                        font: {
                            fontSize: 14,
                            textAlign: 'center'
                        }
                    }
                    this.inputValue = ''
                    this.inputAlign = 'center'
                    this.show4 = true
                    this.$nextTick(() => {
                        this.$refs.field.focus()
                    })
                    break
                // 前面
                case '5':
                    if (this.canvas.activeLayer.pens.length) {
                        this.canvas.top(this.canvas.activeLayer.pens[0])
                        this.canvas.render()
                    }
                    break
                case '6':
                    if (this.canvas.activeLayer.pens.length) {
                        this.canvas.bottom(this.canvas.activeLayer.pens[0])
                        this.canvas.render()
                    }
                    break
            }
        },
        /**
         *  素材相关
         */
        // 根据素材类别id 查询素材列表
        handleChangeSucaiTab(id) {
          this.getSucaiList(id)
        },
        // 选中素材
        handleAddSucai(item) {
          this.canvas.addNode({
            rect: {
                x: 170,
                y: 75,
              width: 50,
              height: 50
            },
            image: item.imgUrl,
            name: 'image'
          },true)
          this.canvas.render()
        },
        // 确认选择素材
        handleConfirm2() {
            this.show2 = false
        },
        onLoad2() {
            // 加载状态结束
            this.loading2 = false;
            // 数据全部加载完成
            if (this.dataList2.length >= this.total2) {
                this.finished2 = true;
            }
        },
        /**
         *  文本相关
         */
        handleChangeInputAlign(value) {
            this.inputAlign = value
            this.textNode.font.textAlign = value
            this.canvas.render()
            this.$nextTick(() => {
                this.$refs.field.focus()
            })
        },
        // 文本编辑确认
        handleConfirmText() {
            console.log('this.canvas.activeLayer.pens',)
            if (this.canvas.activeLayer.pens.length) {
                this.canvas.activeLayer.pens[0].text = this.inputValue
            } else {
                this.canvas.addNode({
                    text: this.inputValue,
                    rect: {
                        x: 0,
                        y: 0,
                        width: 250,
                        height: 50
                    },
                    font: {
                        color: '#000',
                        textAlign: this.inputAlign
                    },
                    name: 'text'
                },false)
            }
          this.canvas.render()
          this.show4 = false
        },
        // 确认文本字体 颜色等配置
        handleChangeFont(value,name) {
            console.log('加载字体value',value,name)
            this.loadfont(name).then(res => {
                console.log('加载字体成功',name)
                this.textNode.font.fontFamily = name
                this.canvas.render()
            })
        },
        handleChangeFontColor(value,name) {
          console.log(value,name)
            this.textNode.font.color = name
            this.canvas.render()
        },
        handleChangeFOntSisze(value) {
            this.textNode.font.fontSize = value
            this.canvas.render()
        },
        // 文本菜单选中
        handleChangeFunc3(item) {
            this.currentActiveFunc3 = item.id
            switch (item.id) {
              // 删除文字节点
                case '1':
                    this.canvas.delete()
                    this.show3 = false
                    break
              // 编辑文字
                case '2':
                    this.inputValue = this.textNode.text
                    this.inputAlign = this.textNode.font.textAlign
                    this.show4 = true
                    this.$nextTick(() => {
                      this.$refs.field.focus()
                    })
                    break
                // 字体
                case '3':
                    this.tabActiveName33 = ''
                    break
                // 字号
                case '4':
                    break
                // 颜色
                case '5':
                    break
                // 前面
                case '6':
                    if (this.canvas.activeLayer.pens.length) {
                        this.canvas.top(this.canvas.activeLayer.pens[0])
                        this.canvas.render()
                    }
                    break
                // 背面
                case '7':
                    if (this.canvas.activeLayer.pens.length) {
                        this.canvas.bottom(this.canvas.activeLayer.pens[0])
                        this.canvas.render()
                    }
                    break

            }
        },
    }
}
</script>

<style lang="less">
@import "~@/style/index.css";
@import "~@/style/desgin.less";

</style>
